// Scripts/Tiles/Tile.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Tile : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [Header("Tile组件")]
    public Image tileImage;
    public Animator animator;
    
    [Header("Tile属性")]
    public int tileType;
    public int gridX;
    public int gridY;
    public bool isMatched;
    public bool isEmpty;
    
    // 颜色配置（根据类型）
    private static Color[] tileColors = new Color[]
    {
        Color.red, Color.blue, Color.green, Color.yellow, Color.magenta, Color.cyan
    };
    
    // 事件
    public System.Action<Tile> OnTileSelected;
    public System.Action<Tile> OnTileDeselected;
    
    public void Initialize(int x, int y, int type)
    {
        gridX = x;
        gridY = y;
        tileType = type;
        isMatched = false;
        isEmpty = false;
        
        UpdateVisuals();
    }
    
    public void UpdateVisuals()
    {
        if (tileImage != null)
        {
            tileImage.color = tileColors[tileType % tileColors.Length];
        }
    }
    
    public void OnPointerDown(PointerEventData eventData)
    {
        OnTileSelected?.Invoke(this);
    }
    
    public void OnPointerUp(PointerEventData eventData)
    {
        OnTileDeselected?.Invoke(this);
    }
    
    public void SetMatched(bool matched)
    {
        isMatched = matched;
        if (matched && animator != null)
        {
            animator.SetTrigger("Match");
        }
    }
    
    public void Clear()
    {
        isEmpty = true;
        // 播放消失动画
        if (animator != null)
        {
            animator.SetTrigger("Clear");
        }
        else
        {
            gameObject.SetActive(false);
        }
    }
}